package com.cloud.auth.biz.service;

import com.cloud.auth.biz.jwt.user.UserCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author 王霄
 * @date 2022/6/17 16:03
 */
@Service
public class UserCacheService {

    private static final String USER_TOKEN_KEY_PREFIX = "user:%s:token";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void saveUserCache(UserCache userCache) {
        String key = buildKey(userCache.getUserId());
        redisTemplate.opsForValue().set(key, userCache, Duration.ofDays(1));
    }

    public UserCache getUserCache(String userId) {
        return (UserCache) redisTemplate.opsForValue().get(buildKey(userId));
    }

    public void delUserCache(String userId) {
        redisTemplate.delete(buildKey(userId));
    }

    private String buildKey(String userId) {
        return String.format(USER_TOKEN_KEY_PREFIX, userId);
    }
}
